package com.aebiz.usercenter.common.util;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component("springEmailUtil")
public class SpringEmailUtil {

	/*邮局*/
	@Resource
	private JavaMailSender javaMailSender;
	/*信件*/
	@Resource
	private SimpleMailMessage mailMessage;
	
	/**
	 * 发信的方法
	 * @param to 收件人
	 * @param subject 标题(信的)
	 * @param content 信的内容
	 * @return true:发送成功,false表示发送失败
	 */
	public boolean send(String to,String subject,String content){
		
		try
		{
			/* 要把信件设置完成 */
			this.mailMessage.setTo(to);
			this.mailMessage.setSubject(subject);
			this.mailMessage.setText(content);
			
			/* 邮递发信 */
			this.javaMailSender.send(mailMessage);
			return true ;
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("发送失败了:to:{},subject:{},content:{}==",to,subject,content,e);
		}
		return false ; 
	}
	
	/**
	 * 发信的方法
	 * @param to 收件人
	 * @param subject 标题(信的)
	 * @param content 信的内容
	 * @return true:发送成功,false表示发送失败
	 */
	public boolean sentHtml(String to,String subject,String content)
	{
		
		try {
			MimeMessage message=this.javaMailSender.createMimeMessage();
			/*信件的工具类*/
			MimeMessageHelper messageHelper=new MimeMessageHelper(message, "UTF-8");
			/* 要把信件设置完成 */
			/* 发件人从配置文件中取 */
			messageHelper.setFrom(this.mailMessage.getFrom());
			messageHelper.setTo(to);
			messageHelper.setSubject(subject);
			/*
			 * 参数二:是否解析html,true:解析
			 * */
			messageHelper.setText(content, true);
			
			/*邮递发信*/
			this.javaMailSender.send(message);
			return true;
		} catch (Exception e) {
			ConstatFinalUtil.SYS_LOGGER.error("发送失败了:to:{},subject:{},content:{}==",to,subject,content,e);
		}
		return false ; 
	}
}
